sap.ui.define([
    "sap/ui/core/Messaging",
    "sap/ui/core/mvc/Controller",
    "sap/ui/model/json/JSONModel",
    "sap/ui/core/Fragment",
    "sap/m/MessageToast",
	"sap/m/MessageBox",
    "sap/ui/model/Sorter",
	"sap/ui/model/Filter",
	"sap/ui/model/FilterOperator",
	"sap/ui/model/FilterType",
],
    /**
     * @param {typeof sap.ui.core.mvc.Controller} Controller
     */
    function (Messaging, Controller, JSONModel, Fragment, MessageToast, MessageBox, Sorter, Filter, FilterOperator, FilterType) {
        "use strict";

        

        return Controller.extend("com.aspn.product.product.controller.productList", {
            onInit: function () {
                this._initData();
            },
            
            /**
             * 초기화 데이터 
            */
            _initData: function () {
                
                var oMessageManager = sap.ui.getCore().getMessageManager(),
				oMessageModel = oMessageManager.getMessageModel(),
				oMessageModelBinding = oMessageModel.bindList("/", undefined, [],
					new Filter("technical", FilterOperator.EQ, true));

                oMessageModelBinding.attachChange(this.onMessageBindingChange, this);
                this._bTechnicalErrors = false;

                //Excel UpLoad Data
                this.excelModel = new JSONModel();
                this.getView().setModel(this.excelModel, "excelModel");

                //View Seting
                var oViewData = {
                    busy : true,
                    hasUIChanges : false,
					usernameEmpty : true,
                    order : 0
                };
                var oModel = new JSONModel(oViewData);
			    this.getView().setModel(oModel, "appView");


            },

            onMessageBindingChange : function (oEvent) {
                var aContexts = oEvent.getSource().getContexts(),
				aMessages,
				bMessageOpen = false;

                if (bMessageOpen || !aContexts.length) {
                    return;
                }

                // Extract and remove the technical messages
                aMessages = aContexts.map(function (oContext) {
                    return oContext.getObject();
                });
                sap.ui.getCore().getMessageManager().removeMessages(aMessages);

                this._setUIChanges(true);
                this._bTechnicalErrors = true;
                
                var oBinding = this.byId("idProductTable").getBinding("items");
                oBinding.resetChanges();
                oBinding.refresh();

                // MessageBox.error(aMessages[0].message, {
                //     id : "serviceErrorMessageBox",
                //     onClose : function () {
                //         bMessageOpen = false;
                //     }
                // });

                bMessageOpen = true;
            },

            _getText : function (sTextId, aArgs) {
                return this.getOwnerComponent().getModel("i18n").getResourceBundle().getText(sTextId, aArgs);
            },

            _setUIChanges : function (bHasUIChanges) {
                if (this._bTechnicalErrors) {
                    // If there is currently a technical error, then force 'true'.
                    bHasUIChanges = true;
                } else if (bHasUIChanges === undefined) {
                    bHasUIChanges = this.getView().getModel().hasPendingChanges();
                }
                var oModel = this.getView().getModel("appView");
                oModel.setProperty("/hasUIChanges", bHasUIChanges);
            },
            /**
             * ===============Action================
             * =============onRefresh===============
             */
            onRefresh : function () {

                var oBinding = this.byId("idProductTable").getBinding("items");
    
                if (oBinding.hasPendingChanges()) {
                     MessageBox.error(this._getText("refreshNotPossibleMessage"));
                     return;
                }
                oBinding.refresh();
                MessageToast.show(this._getText("refreshSuccessMessage"));
            },
            /**
             * ===============Action================
             * =============onSearch================
             */
            onSearch : function () {
                var oView = this.getView(),
                    sValue = oView.byId("searchField").getValue(),
                    oFilter = new Filter("Product", FilterOperator.Contains, sValue);
    
                oView.byId("idProductTable").getBinding("items").filter(oFilter, FilterType.Application);
            },
            
            /**
             * ===============Action================
             * ==============Save Excel Data PopButton================
             */
            onSavePop: function(oEvent) {
                var oTable = this.byId("idProductTable");
                var oBinding = oTable.getBinding("items");
                // var oBinding = this.getView().getBinding();
                
                //Excel Data 가져오기
                var oExlData = this.getView().getModel("excelModel");
                var exlArray = oExlData.getData().items;
                for ( let i = 0; i < exlArray.length; i++ ){
                    
                    oBinding.create({
                        "Product" : exlArray[i].ProductID,
                        "ProductType" : exlArray[i].ProductType,
                        "ProductGroup" : exlArray[i].ProductGroup,
                        "BaseUnit" : exlArray[i].BaseUnit,
                        "IndustrySector" : "M",
                        "_ProductDescription" : [
                            { 
                                "Language" : "3" ,
                                "ProductDescription" : exlArray[i].ProductDes,
                                "Product" : exlArray[i].ProductID
                            }
                        ]
                    }, false );
                }
          
                this._setUIChanges();
                //this._onBatchSave();

                this.getView().byId("mainDialog").close();
            },
            
            _onBatchSave:function () {
                var fnSuccess = function () {
                    MessageToast.show(this._getText("changesSentMessage"));
                    this._setUIChanges(false);

                }.bind(this);
    
                var fnError = function (oError) {
                    this._setUIChanges(false);
                    MessageBox.error(oError.message);

                }.bind(this);

                this.getView().getModel().submitBatch("peopleGroup").then(fnSuccess, fnError);
            },
            onDelete : function () {
                var oContext,
                    oSelected = this.byId("idProductTable").getSelectedItem();
     
                if (oSelected) {
                    oContext = oSelected.getBindingContext();
           
                    oContext.delete().then(function () {
                   
                    }.bind(this), function (oError) {
           
                    }.bind(this));

                    this._setUIChanges(true);
                }

                this._onBatchSave();
            },

            

            onUpload:function(oCtx) {
                // this._import(oCtx.getParameter("files") && oCtx.getParameter("files")[0]);
                let file = oCtx.getParameter("files") && oCtx.getParameter("files")[0];

                var that = this;
                var excelData = {};
               
                if (file && window.FileReader) {
                    
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var data = e.target.result;
                        
                        var workbook = XLSX.read(data, {
                            type: 'binary'
                        });
                        
                        workbook.SheetNames.forEach(function (sheetName) {
                            // Here is your object for every sheet in workbook
                            excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
                        });
                        // Setting the data to the local model 

                        that.excelModel.setData({
                            items: excelData
                        });
                        that.excelModel.refresh(true);
                        that._openDialog();
                    };
                    reader.onerror = function (ex) {
                        console.log(ex);
                    };
                    reader.readAsBinaryString(file);
                }
            },

            _import: function (file) {
                
                var that = this;
                var excelData = {};
               
                if (file && window.FileReader) {
                    
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var data = e.target.result;
                        
                        var workbook = XLSX.read(data, {
                            type: 'binary'
                        });
                        
                        workbook.SheetNames.forEach(function (sheetName) {
                            // Here is your object for every sheet in workbook
                            excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
                        });
                        // Setting the data to the local model 

                        that.excelModel.setData({
                            items: excelData
                        });
                        that.excelModel.refresh(true);
                        that._openDialog();
                    };
                    reader.onerror = function (ex) {
                        console.log(ex);
                    };
                    reader.readAsBinaryString(file);
                }
    
            },

            _openDialog:function() {
            
                if (!this.pDialog) {
                    this.pDialog = this.loadFragment({
                        name: "com.aspn.product.product.view.fragment.MPDialog"
                    });
                } 
                this.pDialog.then(function(oDialog) {
                    oDialog.open();
                });
            
            },


            onClosePop:function (oEvent) {
                this.getView().byId("mainDialog").close();
            },
            
            /**
             * 자재 마스터 F4 
            */
            showValueHelp:function(oEvent) {
                var oView = this.getView();
                if (!this._pValueHelpDialog) {
                    this._pValueHelpDialog = Fragment.load({
                        id: oView.getId(),
                        name: "com.aspn.product.product.view.fragment.ProductType_ValueHelp",
                        controller: this
                    
                    }).then(function (oValueHelpDialog) {
                        oView.addDependent(oValueHelpDialog);
                        return oValueHelpDialog;
                    
                    });
                }

                this._pValueHelpDialog.then(function(oValueHelpDialog) {
                    oValueHelpDialog.open();
                }.bind(this));
            },
           
            //Value Help Dialog Product Type
            handleConfirm: function(oEvent) {
                alert("handleConfirm");
                //var oBinding = oEvent.getSource().getBinding("items");
                var aContexts = oEvent.getParameter("selectedContexts");

                if (aContexts && aContexts.length) { 
                    //aContexts[0].getObject()
                }
            }
            

        });
    });
